// 和用户相关状态管理

import { createSlice } from "@reduxjs/toolkit";
import { request, setToken as _setToken, getToken, removeToken } from "@/utils";
import { LoginAPI, getProfileAPI } from "@/apis/user";
const userStore = createSlice({
  name: "user",
  // 数据状态
  initialState: {
    token: getToken() || "",
    userInfo: {},
  },

  // 同步修改方法
  reducers: {
    setToken(state, action) {
      console.log("我能触发吗");
      _setToken(action.payload);
      state.token = action.payload;
    },
    getUserInfo(state, action) {
      state.userInfo = { ...action.payload };
    },
    clearuserInfo(state, action) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
});

// 解构actionCreater
const { setToken, getUserInfo, clearuserInfo } = userStore.actions;

// 获取reducer函数
const userReducer = userStore.reducer;

// 异步方法 登陆获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    try {
      // 发送异步请求，并等待返回结果
      // const res = await request.post("/authorizations", {
      //   mobile: "13800000002",
      //   code: "246810",
      // });
      const res = await LoginAPI({
        mobile: "13800000002",
        code: "246810",
      });

      console.log("res", res.data.token);

      // 提交同步 action 进行 token 存储
      dispatch(setToken(res.data.token));
    } catch (error) {
      console.error("登录请求失败", error);
    }
  };
};

// 异步请求用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    try {
      // 发送异步请求，并等待返回结果
      const res = await getProfileAPI();
      console.log("res", res.data);
      // 提交同步 action 进行 token 存储
      dispatch(getUserInfo(res.data));
    } catch (error) {}
  };
};

export { fetchLogin, setToken, getUserInfo, fetchUserInfo, clearuserInfo };
export default userReducer;
